package com.astn.bks;

import java.util.Timer;
import java.util.TimerTask;

import com.astn.bks.util.WebserviceUtils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class ProviderService extends Service {

	private Timer timer = new Timer();
	private Context context;
	private NotificationManager nManager;
	public static int QUOTE_NOTIFICATION = 881;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		context = this;
		nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		startService();

	}

	private void startService() {
		timer.scheduleAtFixedRate(new STask(), 0, 20000);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		timer.cancel();
	}

	private final class STask extends TimerTask {

		@Override
		public void run() {
			// If network available
			if (isNetworkAvailable()) {
				// toastHandle.sendEmptyMessage(0);
				// check and get request on my location
				int messageCount = 0;
				try {
					messageCount = (Integer) WebserviceUtils.call("com_xmlrpc",
							"checkNotify", null);
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (messageCount > 0) {
					Notification notify = new Notification(R.drawable.message,
							"Quote: new message", System.currentTimeMillis());
					String contentTitle = "Quote: new message";
					String contentText = String.valueOf(messageCount) + " come";
					Intent callIntent = new Intent(ProviderService.this,
							PostRequest.class);
					PendingIntent pIntent = PendingIntent.getActivity(
							ProviderService.this, 0, callIntent, 0);
					notify.setLatestEventInfo(context, contentTitle,
							contentText, pIntent);
					nManager.notify(QUOTE_NOTIFICATION, notify);
				}

			}
		}

	}

	private final Handler toastHandle = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Toast.makeText(getApplicationContext(), "Time up",
					Toast.LENGTH_SHORT).show();
		}

	};

	private boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null;
	}

}
